import Toast from 'tdesign-miniprogram/toast/index';
import { fetchDeliveryAddress } from '../../../../services/address/fetchAddress';
import { areaData } from '../../../../config/index';
import { rejectAddress } from './util';
// 接口
import { fetchAddressAdd, fetchAddressInfo, fetchAddressUpdate } from '~/request/api';

const innerPhoneReg = '^1(?:3\\d|4[4-9]|5[0-35-9]|6[67]|7[0-8]|8\\d|9\\d)\\d{8}$';
const innerNameReg = '^[a-zA-Z\\d\\u4e00-\\u9fa5]+$';

Page({
  options: {
    multipleSlots: true,
  },
  externalClasses: ['theme-wrapper-class'],
  data: {
    locationState: {
      labelIndex: null,
      cityCode: '',
      cityName: '',
      countryCode: '',
      countryName: '',
      detailAddress: '',
      districtCode: '',
      districtName: '',
      is_def: false,
      name: '',
      phone: '',
      provinceCode: '',
      provinceName: '',
      isEdit: false,
      isOrderDetail: false,
      isOrderSure: false,
    },
    areaData: areaData,
    areaPickerVisible: false,
    submitActive: false,
    visible: false,
    labelValue: '',
    columns: 3,
  },
  privateData: {
    verifyTips: '',
  },
  onLoad(options) {
    this.setData({ addressId: options?.id })
    this.init(options?.id);
  },

  onUnload() {
    if (!this.hasSava) {
      rejectAddress();
    }
  },

  hasSava: false,

  // 收货地址信息
  async addressInfo(id) {
    try {
      const res = await fetchAddressInfo({ address_id: id });
      let _locationState = { ...res, provinceCode: res.p_code, provinceName: res.p_name, cityCode: res.c_code, cityName: res.c_name, districtCode: res.a_code, districtName: res.a_name, detailAddress: res.address, is_def: res.is_def == 2 ? true : false }
      this.setData({ locationState: _locationState }, () => {
        const { isLegal, tips } = this.onVerifyInputLegal();
        this.setData({
          submitActive: isLegal,
        });
        this.privateData.verifyTips = tips;
      });
    } catch (error) {
      console.log(error);
    }
  },

  // 添加地址
  async addressAdd(params) {
    try {
      await fetchAddressAdd(params);
      Toast({
        context: this,
        selector: '#t-toast',
        message: '添加成功',
        icon: '',
        duration: 1000,
      });

      setTimeout(() => {
        wx.navigateBack({ delta: 1 });
      }, 1000)
    } catch (error) {
      console.log(error);
    }
  },

  // 修改地址
  async addressUpdate(params) {
    try {
      await fetchAddressUpdate(params);
      Toast({
        context: this,
        selector: '#t-toast',
        message: '修改成功',
        icon: '',
        duration: 1000,
      });

      setTimeout(() => {
        wx.navigateBack({ delta: 1 });
      }, 1000)
    } catch (error) {
      console.log(error);
    }
  },

  init(id) {
    if (id) {
      this.addressInfo(Number(id));
    }
  },

  onInputValue(e) {
    const { item } = e.currentTarget.dataset;
    if (item === 'address') {
      const { selectedOptions = [] } = e.detail;
      console.log(e.detail);
      this.setData(
        {
          'locationState.provinceCode': selectedOptions[0].value,
          'locationState.provinceName': selectedOptions[0].label,
          'locationState.cityName': selectedOptions[1].label,
          'locationState.cityCode': selectedOptions[1].value,
          'locationState.districtCode': selectedOptions[2].value,
          'locationState.districtName': selectedOptions[2].label,
          areaPickerVisible: false,
        },
        () => {
          const { isLegal, tips } = this.onVerifyInputLegal();
          this.setData({
            submitActive: isLegal,
          });
          this.privateData.verifyTips = tips;
        },
      );
    } else {
      const { value = '' } = e.detail;
      this.setData(
        {
          [`locationState.${item}`]: value,
        },
        () => {
          const { isLegal, tips } = this.onVerifyInputLegal();
          this.setData({
            submitActive: isLegal,
          });
          this.privateData.verifyTips = tips;
        },
      );
    }
  },
  onPickArea() {
    this.setData({ areaPickerVisible: true });
  },
  onCheckDefaultAddress({ detail }) {
    const { value } = detail;
    this.setData({
      'locationState.is_def': value,
    });
  },

  onVerifyInputLegal() {
    const { name, phone, detailAddress, districtName } = this.data.locationState;
    const prefixPhoneReg = String(this.properties.phoneReg || innerPhoneReg);
    const prefixNameReg = String(this.properties.nameReg || innerNameReg);
    const nameRegExp = new RegExp(prefixNameReg);
    const phoneRegExp = new RegExp(prefixPhoneReg);

    if (!name || !name.trim()) {
      return {
        isLegal: false,
        tips: '请填写收货人',
      };
    }
    if (!nameRegExp.test(name)) {
      return {
        isLegal: false,
        tips: '收货人仅支持输入中文、英文（区分大小写）、数字',
      };
    }
    if (!phone || !phone.trim()) {
      return {
        isLegal: false,
        tips: '请填写手机号',
      };
    }
    if (!phoneRegExp.test(phone)) {
      return {
        isLegal: false,
        tips: '请填写正确的手机号',
      };
    }
    if (!districtName || !districtName.trim()) {
      return {
        isLegal: false,
        tips: '请选择省市区信息',
      };
    }
    if (!detailAddress || !detailAddress.trim()) {
      return {
        isLegal: false,
        tips: '请完善详细地址',
      };
    }
    if (detailAddress && detailAddress.trim().length > 50) {
      return {
        isLegal: false,
        tips: '详细地址不能超过50个字符',
      };
    }
    return {
      isLegal: true,
      tips: '添加成功',
    };
  },

  formSubmit() {
    const { submitActive } = this.data;
    if (!submitActive) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: this.privateData.verifyTips,
        icon: '',
        duration: 1000,
      });
      return;
    }
    const { locationState, addressId } = this.data;

    this.hasSava = true;
    let obj = {
      id: addressId,
      phone: locationState.phone,
      name: locationState.name,
      code: locationState.districtCode,
      address: locationState.detailAddress,
      is_def: locationState.is_def ? 2 : 1,
    }

    if (addressId) {
      this.addressUpdate(obj)
    } else {
      this.addressAdd(obj)
    }
  },
});
